<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <!-- <el-form-item label="项目描述">
          <el-select
            v-model="searchParam.projectId"
            placeholder="请选择项目描述"
            clearable
            filterable
            @change="projectChange"
          >
            <el-option
              v-for="item in projectList"
              :key="item.id"
              :label="item.projectCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工序编码">
          <el-select
            v-model="searchParam.processId"
            placeholder="请选择工序编码"
            clearable
            :disabled="!searchParam.projectId"
            filterable
            @change="processChange"
          >
            <el-option
              v-for="item in processList"
              :key="item.id"
              :label="item.processCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="生产设备">
          <el-select
            v-model="searchParam.equipId"
            placeholder="请选择生产设备"
            clearable
            filterable
            :disabled="!searchParam.processId"
            @change="equipChange"
          >
            <el-option
              v-for="item in equipList"
              :key="item.id"
              :label="item.equipCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品型号">
          <el-select
            v-model="searchParam.modelId"
            placeholder="请选择产品型号"
            clearable
            filterable
            @change="productChange"
          >
            <el-option
              v-for="item in productList"
              :key="item.id"
              :label="item.productCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->
        <SearchFormGroup
          :data="searchParam"
          @change-search="handleSearchChange"
        />
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <!-- <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="deleteItem()"
          ><i-ep-delete />删除</el-button
        > -->
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        :header-cell-style="{ textAlign: 'center' }"
      >
        <!-- <el-table-column type="selection" width="55" align="center" /> -->

        <el-table-column
          label="生产节拍（秒）"
          prop="tactTime"
          min-width="100"
          show-overflow-tooltip
          align="right"
        />

        <el-table-column
          label="项目描述"
          prop="projectCode"
          min-width="100"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="工序编码"
          prop="processName"
          min-width="100"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="生产设备"
          prop="equipCode"
          min-width="100"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="产品型号"
          prop="modelCode"
          min-width="100"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="80" align="center">
          <template #default="scope">
            <!-- <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button> -->
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="编辑"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialog(scope.row)"
              >
                <i-ep-edit />
              </el-button>
            </el-tooltip>
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="删除"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="deleteItem(scope.row.id)"
              >
                <i-ep-delete />
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <pcmtacttime-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : getTableList())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import SearchFormGroup from "@/views/pcm/pcmMonitoring/components/SearchFormGroup.vue";
import request from "@/utils/request";
import {
  getMdmproductinfosApi,
  getMdmprojectinfosApi,
  getMdminspectiontoolApi,
  getSpecificListApi,
  getMdmProcessEquipApi,
  getMdmProcessProjectApi,
} from "@/utils/commonData";
defineOptions({
  name: "PCMPCMTACTTIME",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/dmpDosPcm/pcmtacttime/queryByPage";

// 处理传回数据
const handleSearchChange = (data) => {
  Object.assign(searchParam.value, data);
  // 可执行字段相关的特定逻辑
};
// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  processId: "",
  processCode: "",
  processName: "",
  equipId: "",
  equipCode: "",
  equipName: "",
  projectId: "",
  projectCode: "",
  projectName: "",
  modelId: "",
  modelCode: "",
  modelName: "",
};

const deleteParam = {
  api: "/dmpDosPcm/pcmtacttime/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/dmpDosPcm/pcmtacttime/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开生产节拍表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "生产节拍-修改";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "生产节拍-新增";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开生产节拍表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "生产节拍-详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

// async function deleteItem(id: any) {
//   ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
//     confirmButtonText: "确定",
//     cancelButtonText: "取消",
//     type: "warning",
//   }).then(async () => {
//     const { data } = await request({
//       url: `/dmpDosPcm/pcmtacttime/deleteItem/${id}`,
//       method: "post",
//     });
//     search();
//   });
// }

// 通过工序查询设备列表
const equipList = ref(<any>[]);
async function getEquipList(id: string) {
  equipList.value = (await getMdmProcessEquipApi({ processId: id })) || [];
}
function equipChange(id: string) {
  if (id) {
    const current: any =
      equipList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.equipCode = current.equipCode || "";
  } else {
    searchParam.value.equipCode = "";
  }
}

// 获取工序列表
const processList = ref<any>([]);
async function getProcessList(id: string) {
  processList.value = (await getMdmProcessProjectApi({ projectId: id })) || [];
}
async function processChange(id: string) {
  searchParam.value.equipId = "";
  searchParam.value.equipCode = "";
  if (id) {
    const current: any =
      processList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.processCode = current.processCode || "";
    await getEquipList(id);
  } else {
    searchParam.value.processCode = "";
    equipList.value = [];
  }
}

// 获取项目列表
const projectList = ref<any>([]);
async function getProjectList() {
  projectList.value = (await getMdmprojectinfosApi({})) || [];
}
async function projectChange(id: string) {
  searchParam.value.equipId = "";
  searchParam.value.equipCode = "";
  searchParam.value.processId = "";
  searchParam.value.processCode = "";
  if (id) {
    const current: any =
      projectList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.projectCode = current.projectCode || "";
    await getProcessList(id);
    await getProductList(id);
  } else {
    searchParam.value.projectCode = "";
    equipList.value = [];
    processList.value = [];
    productList.value = [];
  }
}

// 获取产品型号列表
const productList = ref<any>([]);
async function getProductList(id: string) {
  productList.value = (await getMdmproductinfosApi({ projectId: id })) || [];
}
function productChange(id: string) {
  if (id) {
    const current: any =
      productList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.modelCode = current.productCode || "";
  } else {
    searchParam.value.modelCode = "";
  }
}

async function deleteItem(id: any) {
  if (id) {
    ElMessageBox.confirm("确认删除该数据项?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(async () => {
      await request({
        url: `/dmpDosPcm/pcmtacttime/deleteItem/${id}`,
        method: "post",
        data: {},
      }).then((res) => {
        ElMessage.success("删除成功！");
        search();
      });
    });
  } else {
    ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(async () => {
      await request({
        url: `/dmpDosPcm/pcmtacttime/delete`,
        method: "post",
        data: { ids: ids.value },
      }).then((res) => {
        ElMessage.success("删除成功！");
        search();
      });
    });
  }
}

onMounted(() => {
  // 获取项目列表
  getProjectList();
  // 获取产品型号列表
  // getProductList();
});
</script>
